#include "esp_log.h"
#include "esp_http_server.h"
#include "server.h"
#include "camera_stream.h"
// 移除对ai_chat.h的引用

static const char *TAG = "SERVER";
static httpd_handle_t server = NULL;

// 摄像头和AI对话页面HTML内容
static const char* CAMERA_HTML = 
"<!DOCTYPE html>"
"<html>"
"<head>"
"<title>ESP32-CAM AI对话</title>"
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
"<style>"
"body { font-family: Arial; margin: 20px; background-color: #f0f0f0; }"
".container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }"
"h1 { text-align: center; color: #333; }"
"#cameraImage { width: 100%; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; }"
"#streamImage { width: 100%; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; }"
"</style>"
"</head>"
"<body>"
"<div class='container'>"
"<h1>ESP32-CAM AI相机</h1>"
"<h3>静态图像 (每秒刷新)</h3>"
"<img id='cameraImage' src='/image' alt='摄像头图像'>"
"<h3>实时视频流</h3>"
"<img id='streamImage' src='/stream' alt='实时视频流'>"
"<p>提示：按下开发板上的按键可以拍照并发送到AI进行分析</p>"
"</div>"
"<script>"
"// 自动刷新静态图像"
"setInterval(function() {"
"    document.getElementById('cameraImage').src = '/image?t=' + new Date().getTime();"
"}, 1000);"
"</script>"
"</body>"
"</html>";

// 处理根页面请求
static esp_err_t camera_index_handler(httpd_req_t *req) {
    ESP_LOGI(TAG, "收到摄像头页面请求");
    httpd_resp_set_type(req, "text/html");
    return httpd_resp_send(req, CAMERA_HTML, HTTPD_RESP_USE_STRLEN);
}

// URI处理配置
static const httpd_uri_t camera_index = {
    .uri = "/",
    .method = HTTP_GET,
    .handler = camera_index_handler,
    .user_ctx = NULL
};

static const httpd_uri_t image = {
    .uri = "/image",
    .method = HTTP_GET,
    .handler = image_handler,
    .user_ctx = NULL
};

static const httpd_uri_t stream = {
    .uri = "/stream",
    .method = HTTP_GET,
    .handler = stream_handler,
    .user_ctx = NULL
};

// 启动HTTP服务器
void start_http_server(void) {
    ESP_LOGI(TAG, "启动HTTP服务器...");
    
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    config.server_port = 80;  // 使用80端口
    
    if (httpd_start(&server, &config) == ESP_OK) {
        // 注册URI处理器
        httpd_register_uri_handler(server, &camera_index);
        httpd_register_uri_handler(server, &image);
        httpd_register_uri_handler(server, &stream);
        
        ESP_LOGI(TAG, "HTTP服务器已启动，端口: %d", config.server_port);
    } else {
        ESP_LOGE(TAG, "启动HTTP服务器失败");
    }
}

// 停止HTTP服务器
void stop_http_server(void) {
    if (server) {
        httpd_stop(server);
        server = NULL;
        ESP_LOGI(TAG, "HTTP服务器已停止");
    }
}